package com.sky.service.impl;

import cn.hutool.db.sql.Order;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional  //事务注解
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理业务异常（地址簿为空，购物车数据为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断购物车数据，通过用户id查询
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        //将DTO对象拷贝到实体类中
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //设置用户id
        orders.setUserId(userId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态 为未支付
        orders.setPayStatus(Orders.UN_PAID);
        //设置订单状态  为待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置当前订单号，使用时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置用户手机号，通过addressBook表查询，在校验时已经查询过
        orders.setPhone(addressBook.getPhone());
        //设置用户名
        orders.setUserName(addressBook.getConsignee());
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //设置地址
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        //返回主键值到参数对象中，后续插入订单详细表数据时使用
        orderMapper.insert(orders);

        //向订单详细表插入多条数据（一个订单中每一个商品都是详细表的一条数据，一对多）
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            //将购物车对象拷贝到实体类中
            BeanUtils.copyProperties(cart, orderDetail);
            //设置订单id
            orderDetail.setOrderId(orders.getId());
            //插入list
            orderDetailList.add(orderDetail);
        });
        //批量插入数据库
        orderDetailMapper.insertBatch(orderDetailList);

        //用户下单成功，清空购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装VO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        log.info("支付成功，订单号:{}", outTradeNo);

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //提醒管理端浏览器来单，使用websocket推送消息
        //包含type，orderId，content三个字段，转为JSON，和前端约定的
        //将三个字段封装到Map中，再将Map转为JSON
        Map map = new HashMap();
        map.put("type", 1);  //type:  1表示来单提醒，2表示用户催单  ，和前端约定的
        map.put("orderId", ordersDB.getId());  //订单id
        map.put("content", "订单号：" + outTradeNo);  //提示内容

        //Map转JSON，使用fastjson
         String json = JSON.toJSONString(map);

        //使用websocket推送消息
        webSocketServer.sendToAllClient(json);
    }


    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //查询条件中加入用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        //先查询orders表中订单，再查询orderDetail表中订单详细
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<Orders> ordersList = page.getResult();
        long total = page.getTotal();

        //查询结果封装进vo，同时查询orderDetail表，封装详细信息到vo
        //OrderVO继承orders，包含orders的所有属性
        List<OrderVO> orderVOList = new ArrayList<>();
        if (page != null && page.getTotal() > 0) {
            ordersList.forEach(order -> {
                //通过orderid查询orderDetail表
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());

                OrderVO orderVO = new OrderVO();
                //拷贝属性到vo
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            });
        }

        return new PageResult(total, orderVOList);
    }

    public OrderVO getOrderWithOrderDetailById(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    public void cancel(Long id) {
        //根据id查询订单，查看是否存在
        Orders order = orderMapper.getById(id);

        if (order == null) {
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单非待支付 1 和待接单 2 状态，需电话和商家联系，商家在管理端取消订单
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //订单状态为待接单，用户取消需退款
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            /*weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/

            //退款成功，更改支付状态为 退款2
            order.setPayStatus(Orders.REFUND);
        }

        // 更改订单状态为已取消6，取消原因为用户取消，取消时间
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());

        orderMapper.update(order);
    }


    public void repetition(Long id) {
        //再来一单，将订单详细表中该订单的商品重新添加到购物车中
        //查询订单详细表
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        orderDetailList.forEach(od -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //将订单详细表中的订单商品信息拷贝到购物车中
            BeanUtils.copyProperties(od, shoppingCart);
            //设置用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            //设置时间
            shoppingCart.setCreateTime(LocalDateTime.now());

            //插入到购物车表中
            shoppingCartMapper.insert(shoppingCart);
            //TODO 可以修改为批量插入 insertBatch 在xml中通过<foreach>遍历列表，拼接sql语句
        });

    }

    public PageResult adminPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        long total = page.getTotal();
        List<Orders> ordersList = page.getResult();

        List<OrderVO> orderVOList = new ArrayList<>();
        ordersList.forEach(orders -> {
            //通过orderid查询订单包含的菜品，以字符串形式展示
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
            //获得所有的菜品名称
            List<String> orderDetailDishNameList = new ArrayList<>();
            orderDetailList.forEach(orderDetail -> {
                String name = orderDetail.getName();
                String number = orderDetail.getNumber().toString();
                orderDetailDishNameList.add(name + "*" + number);
            });
            //将list转为，只保留逗号的字符串形式 [a,b,c] -> a,b,c
            String orderDetailListString = String.join(";", orderDetailDishNameList);

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDishes(orderDetailListString);

            orderVOList.add(orderVO);
        });

        return new PageResult(total, orderVOList);
    }

    public OrderStatisticsVO statistics() {
        //各个状态订单数量统计
//        2待接单 3待派送 4派送中
        //在order表中查询状态分别为2，3，4的订单数量
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.CountByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.CountByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.CountByStatus(Orders.DELIVERY_IN_PROGRESS));

        return orderStatisticsVO;
    }

    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
//        改变订单状态status
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(ordersConfirmDTO.getStatus());
        orderMapper.update(orders);
    }

    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //拒单，将状态改为已取消6
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //只有处于待接单2状态才可以拒单
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //用户若已付款，要退款并修改支付状态
        if (orders.getPayStatus() == Orders.PAID) {
            //退款
            /*String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));*/

            orders.setPayStatus(Orders.REFUND);  //设置退款状态
        }
        //更改订单状态为已取消6，取消原因，取消时间
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        orderMapper.update(order);
    }

    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            /*String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));*/

            ordersDB.setPayStatus(Orders.REFUND);  //设置退款状态
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    public void tabStatus(Long id, Integer status) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(status);

        //如果是转为已完成，则设置送达时间字段
        if (status == Orders.COMPLETED) {
            orders.setDeliveryTime(LocalDateTime.now());
        }

        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    public void reminder(Long id) {
        //查询数据库，检查是否有该订单
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //提醒管理端浏览器用户催单
        //包含type，orderId，content三个字段，转为JSON，和前端约定的
        //将三个字段封装到Map中，再将Map转为JSON
        Map map = new HashMap();
        map.put("type", 2);  //type：1表示来单提醒，  2表示用户催单   和前端约定的
        map.put("orderId", id);
        map.put("content", "订单号：" + ordersDB.getNumber());

        //使用fastjson，将map转为json字符串
        String json = JSON.toJSONString(map);

        //使用websocket，将json字符串发送给管理端浏览器
        webSocketServer.sendToAllClient(json);
    }


}
